<?php
	require_once 'Zend/Loader.php';
	Zend_Loader::loadClass('Zend_Gdata');
	Zend_Loader::loadClass('Zend_Gdata_AuthSub');
	Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
	Zend_Loader::loadClass('Zend_Gdata_Calendar');

	require_once('GenusAPIs/GenusApis.php');
	$oOAuthConsumer = new OAuthConsumer("MjEwNV-jK9CigmbdQ_zJa-FU8qDy", "MjEwNV_8vv9S3vRZwSLVItIrsZwu");
	$oGenusApis = new GenusApis($oOAuthConsumer);

	// Connection DB
	include('database_inc.php');
	$db = mysql_connect($server,$gebruikersnaam, $password);
	mysql_select_db($database, $db);
		
	//Check if any changes we're made to events in google calendar and update www's accordingly
		
	$sql = "SELECT * FROM users";
	$result = mysql_query($sql, $db);
	while($regel = mysql_fetch_assoc($result))
		{
			 	//Creating header with AuthSubtoken
				$client = Zend_Gdata_AuthSub::getHttpClient($regel['googleAuthSubToken']);
				// Get all calendars of user
				$gdataCal = new Zend_Gdata_Calendar($client);
				try
				{
			 		$calFeed = $gdataCal->getCalendarListFeed();
				}
				catch(Zend_Gdata_App_HttpException $e) 
				{
					echo 'Er kan geen verbinding gemaakt worden met Google Calendar: '.$e->getMessage().'. Probeer het later nog eens.';
					exit;				 
				} 
			  	
			  	foreach ($calFeed as $calendar) 
				{
					if($calendar->accessLevel == 'owner' || $calendar->accessLevel == 'editor')
					{
						$urlparts = explode('/',$calendar->getAlternateLink()->href);
						$calendarid = array();
						$calendarid[] = $urlparts[5];
					} 
				}
				// Output calendar by date range
				foreach($calendarid as $user)
				{				
						$gdataCal = new Zend_Gdata_Calendar($client);
						$query = $gdataCal->newEventQuery();
						$query->setUser($user);
						$query->setVisibility('private');
						$query->setFutureEvents('true');
						try
						{
							$eventFeed = $gdataCal->getCalendarEventFeed($query);
						}
						catch(Zend_Gdata_App_HttpException $e) 
						{
							echo 'Er kan geen verbinding gemaakt worden met Google Calendar: '.$e->getMessage().'. Probeer het later nog eens';
							exit;						 
						}
					  	  foreach ($eventFeed as $event) 
						  {
								$sql = "SELECT * FROM wwws WHERE hyvesID = '".$regel['hyvesID']."'";
								$result2 = mysql_query($sql, $db);
								$urlparts = explode('/',$event->id->text);
								while($row = mysql_fetch_assoc($result2))
								{
									if ($urlparts[8] == $row['eventID'])
									{
										$description = $event->content->text;
										
										$wwwall = substr_count($description, '[wiewatwaarall]');
										$wwwhyv = substr_count($description, '[wiewatwaarhyvers]'); 
										$wwwfof = substr_count($description, '[wiewatwaarvvv]');
										$wwwvri = substr_count($description, '[wiewatwaarvrienden]');
										if($wwwall == 1)
										{
											$visibility = 'superpublic';
											$sql = "UPDATE wwws SET event = '".$event->content->text."', location = '".$event->where[0]->valueString."', starttime = '".$event->when[0]->startTime."', visibility = '".$visibility."' WHERE eventID = '".$row['eventID']."'";
										}
										elseif($wwwhyv == 1)
										{
											$visibility = 'public';
											$sql = "UPDATE wwws SET event = '".$event->content->text."', location = '".$event->where[0]->valueString."', starttime = '".$event->when[0]->startTime."', visibility = '".$visibility."' WHERE eventID = '".$row['eventID']."'";
										}
										elseif($wwwfof == 1)
										{
											$visibility = 'friends_of_friends';
											$sql = "UPDATE wwws SET event = '".$event->content->text."', location = '".$event->where[0]->valueString."', starttime = '".$event->when[0]->startTime."', visibility = '".$visibility."' WHERE eventID = '".$row['eventID']."'";
										}
										elseif($wwwvri == 1)
										{
											$visibility = 'friend';
											$sql = "UPDATE wwws SET event = '".$event->content->text."', location = '".$event->where[0]->valueString."', starttime = '".$event->when[0]->startTime."', visibility = '".$visibility."' WHERE eventID = '".$row['eventID']."'";
										}
										else
										{
											$sql = "DELETE FROM wwws WHERE eventID = '".$row['eventID']."'";
										}
										mysql_query($sql, $db);
									}
								}
														
						  }
					  	 
				}
		}
	// Add new ww's to database with WWW tag
	$sql = "SELECT * FROM users";
	$result = mysql_query($sql, $db);
	while($regel = mysql_fetch_assoc($result))
		{
			 	//Creating header with AuthSubtoken
				$client = Zend_Gdata_AuthSub::getHttpClient($regel['googleAuthSubToken']);
				// Get all calendars of user
				$gdataCal = new Zend_Gdata_Calendar($client);
			 	try
				{
			 		$calFeed = $gdataCal->getCalendarListFeed();
				}
				catch(Zend_Gdata_App_HttpException $e) 
				{
					echo 'Er kan geen verbinding gemaakt worden met Google Calendar: '.$e->getMessage().'. Probeer het later nog eens';
					exit;				 
				}
			  
			  	foreach ($calFeed as $calendar) 
				{
					if($calendar->accessLevel == 'owner' || $calendar->accessLevel == 'editor')
					{
						$urlparts = explode('/',$calendar->getAlternateLink()->href);
						$calendarid = array();
						$calendarid[] = $urlparts[5];
					} 
				}
				// Output calendar by date range
				foreach($calendarid as $user)
				{				
						$gdataCal = new Zend_Gdata_Calendar($client);
						$query = $gdataCal->newEventQuery();
						$query->setUser($user);
						$query->setVisibility('private');
						$query->setFutureEvents('true');
						try
						{
							$eventFeed = $gdataCal->getCalendarEventFeed($query);
						}
						catch(Zend_Gdata_App_HttpException $e) 
						{
							echo 'Er kan geen verbinding gemaakt worden met Google Calendar: '.$e->getMessage().'. Probeer het later nog eens';
							exit;					 
						}
					  	  foreach ($eventFeed as $event) 
						  {
								$urlparts = explode('/',$event->id->text);
								$description = $event->content->text;
								$aanvang = $event->when[0]->startTime;
								$wwwall = substr_count($description, '[wiewatwaarall]');
								$wwwhyv = substr_count($description, '[wiewatwaarhyvers]'); 
								$wwwfof = substr_count($description, '[wiewatwaarvvv]');
								$wwwvri = substr_count($description, '[wiewatwaarvrienden]');
								$visibility = 'none';
										if($wwwall == 1)
										{
											$visibility = 'superpublic';
										}
										elseif($wwwhyv == 1)
										{
											$visibility = 'public';
										}
										elseif($wwwfof == 1)
										{
											$visibility = 'friends_of_friends';
										}
										elseif($wwwvri == 1)
										{
											$visibility = 'friend';
										}
								if ($visibility != 'none')
								{
									$sql = "INSERT INTO wwws (eventID, hyvesID, event, visibility, location, starttime) VALUES ('".$urlparts[8]."','".$regel['hyvesID']."','".$event->content->text."','".$visibility."','".$event->where[0]->valueString."', '".$aanvang."')";
									mysql_query($sql, $db);
								}
								
														
						  }
					  	 
				}
		}
	
	//Select all WWW's that have passed current timestamp and write them to Hyves
	$sql = "SELECT * FROM wwws WHERE starttime < '".date("Y-m-d H:i:s")."'";
	$result = mysql_query($sql, $db);
	
	if (mysql_num_rows($result) > 0)
	{	
		while($regel = mysql_fetch_assoc($result))
			{
				// Write www's to hyves
				$event = $regel['event'];
				$patterns = array('/wiewatwaarall/','/wiewatwaarhyvers/','/wiewatwaarvvv/','/wiewatwaarvrienden/','/\[/','/\]/');
				$emotion = preg_replace($patterns,'',$event);				
				$where = $regel['location'];
				$visibility = $regel['visibility'];
				$sql = "SELECT * FROM users WHERE hyvesID = '".$regel['hyvesID']."'";
				$result2 = mysql_query($sql, $db);
				$regel2 = mysql_fetch_array($result2);
				$oAccessToken = unserialize($regel2['hyvesAccessTokenObject']);
				$oGenusApis->doMethod("wwws.create", array("emotion" => "$emotion", "where" => "$where", "visibility" => "$visibility"), $oAccessToken);
			}
		$sql = "DELETE FROM wwws WHERE starttime < '".date("Y-m-d H:i:s")."'";
		mysql_query($sql, $db);
	}